<template>
    <div class="content-total">
        <!--部门管理-->
        <div class="left-nav">
            <div class="nav-title">
                <span class="nav-text">部门管理</span>
            </div>
            <el-input
                v-model="companyName"
                placeholder="输入要搜索的部门"
                class="nav-input"
                @input="handleSearch"></el-input>
            <el-tree-v2
                ref="treeRef"
                class="ant-tree zw-tree-box"
                :props="treeProps"
                :filter-method="handleFilterMethod"
                :height="elTreeHeight"
                @node-click="nodeClick"
                @node-expand="onNodeExpand">
                <template #default="{ data }">
                    <div class="hover-text">
                        <div :class="selectId == data.id ? 'hover-detail-color' : 'hover-detail'">
                            {{ data.name
                            }}<span :class="data.is_local ? 'local-color' : 'detail-color'">{{
                                data.is_local ? '(本地)' : '(企微)'
                            }}</span>
                        </div>
                    </div>
                </template>
            </el-tree-v2>
            <div v-if="searchTree.length > 0" class="search-list">
                <el-button
                    v-for="(item, index) in searchTree"
                    :key="index"
                    class="search-detail"
                    type="text"
                    @click="clickSearch(item)">
                    {{ item.name
                    }}<span :class="item.is_local ? 'local-color' : 'detail-color'">{{
                        item.is_local ? '(本地)' : '(企微)'
                    }}</span>
                </el-button>
            </div>
        </div>
        <!---中间栏-->
        <div class="right-content">
            <!--搜索栏-->
            <ZwSearchForm row-num="3" :option="searchOption" @search="search" @reset="reset" />
            <!--table表格-->
            <ZwTable
                ref="tableRef"
                class="table-box"
                tab-h="initial"
                :option="tableOption"
                :fetch-params="state.searchParams"
                :row-key="getRowKey"
                :fetch-api="fetchApi()">
                <template #headerOperateLeft>
                    <div class="table-header-left">
                        <span class="sync_hronize" @click="changeLoading">
                            <el-icon v-if="loadingSync" class="is-loading"><Loading /></el-icon>
                            <el-icon v-else class="sync_icon"><RefreshRight /></el-icon>
                            同步企微组织架构
                        </span>
                        <span class="content-time">最后一次同步时间：{{ updated_at }}</span>
                    </div>
                </template>
                <template #headerOperate>
                    <el-button plain @click="handleConfiguration">高级配置</el-button>
                    <el-button class="content-item" type="primary" @click="addSubAccount">批量开启子账号</el-button>
                </template>
            </ZwTable>
        </div>
        <!--右侧弹出框-->
        <ZWDrawer ref="DrawerRef" @submit="operate">
            <div style="padding: 20px 0">
                <el-form ref="uploadForm" label-position="right" :model="formData" :rules="rules" label-width="auto">
                    <el-form-item label="员工姓名" class="form-item" prop="name">
                        <el-input
                            v-model="formData.name"
                            placeholder="输入成员姓名"
                            class="form-label"
                            :disabled="is_local == 0"></el-input>
                    </el-form-item>
                    <el-form-item label="性别" class="form-item">
                        <el-radio v-model="formData.gender" :label="1" :disabled="is_local == 0">男</el-radio>
                        <el-radio v-model="formData.gender" :label="2" :disabled="is_local == 0">女</el-radio>
                    </el-form-item>
                    <el-form-item label="手机号" class="form-item" prop="mobile">
                        <el-input
                            v-model="formData.mobile"
                            placeholder="输入手机号"
                            maxlength="11"
                            show-word-limit
                            class="form-label"
                            :disabled="is_local == 0"></el-input>
                    </el-form-item>
                    <el-form-item label="部门" class="form-item" prop="departments">
                        <!--部门按钮禁用，企微员工不可编辑部门，目前只有企微员工-->
                        <el-button v-if="is_local == 0" class="form-btns" :disabled="true" @click="Opendeparts(2)">
                            部门
                        </el-button>
                        <el-button
                            v-if="selectDeparts.length == 0"
                            class="form-btns"
                            :disabled="is_local == 0"
                            @click="Opendeparts(2)">
                            部门
                        </el-button>
                        <div v-else class="zw-el-tags">
                            <el-tag
                                v-for="(item, index) in selectDeparts"
                                :key="index"
                                :closable="!isread && is_local !== 0"
                                @close="handleClose(item, 1)">
                                {{ item.name }}
                            </el-tag>
                            <el-link
                                v-if="!isread && is_local !== 0"
                                :underline="false"
                                type="primary"
                                @click="Opendeparts(2)">
                                修改
                            </el-link>
                        </div>
                    </el-form-item>
                    <el-form-item label="标签" class="form-item">
                        <el-button
                            v-if="formData.tags.length == 0 && !editCount"
                            class="form-btns"
                            :disabled="isread"
                            @click="openTagDialog()">
                            标签
                        </el-button>
                        <el-button
                            v-if="formData.tags.length > 0 || editCount"
                            class="form-btns"
                            :disabled="isread"
                            @click="openTagDialog(formData.tags)">
                            已选择{{ formData.tags.length }}个标签
                        </el-button>
                    </el-form-item>
                    <el-form-item v-if="selectDeparts.length > 0" label="身份" class="form-item">
                        <el-radio-group v-model="isSuper" @change="changeRadio">
                            <el-radio :label="1" :disabled="is_local == 0">普通成员</el-radio>
                            <el-radio :label="2" :disabled="is_local == 0">上级</el-radio>
                        </el-radio-group>
                    </el-form-item>
                    <!-- is_sub_account为true是关联子账，满足关联子账号的条件才出现下面这个信息 -->
                    <el-form-item v-if="editCount && is_sub_account" label="企微客易达应用" class="form-item" required>
                        <el-switch v-model="qwasync" :disabled="isread" />
                    </el-form-item>
                    <el-form-item v-if="isSuper == 2" label="负责部门">
                        <div class="zw-el-tags">
                            <el-tag
                                v-for="(item, index) in leaderdept"
                                :key="index"
                                closable
                                @close="handleClose(item, 2)">
                                {{ item.name }}
                            </el-tag>
                            <el-link v-if="!isread" :underline="false" type="primary" @click="Opendeparts(3)">
                                修改
                            </el-link>
                        </div>
                    </el-form-item>
                </el-form>
            </div>
        </ZWDrawer>
        <!--选择部门弹出框-->
        <el-dialog v-model="departVisible" title="选择部门" width="50%" append-to-body class="depart-select">
            <div class="depart-content">
                <div>
                    <el-input
                        v-model="companySearch"
                        style="width: 240px"
                        suffix-icon="Search"
                        placeholder="搜索部门"
                        @input="searchName"></el-input>
                    <el-tree
                        v-if="!companySearch"
                        default-expand-all
                        :data="treeData"
                        :props="defaultProps"
                        @node-click="nodeClick">
                        <template #default="{ node, data }">
                            <span>{{ node.name }}</span>
                            <div class="hover-detail">
                                {{ data.name
                                }}<span :class="data.is_local ? 'local-color' : 'detail-color'">{{
                                    data.is_local ? '(本地)' : '(企微)'
                                }}</span>
                            </div>
                        </template>
                    </el-tree>
                    <div class="depart-detail">
                        <el-button
                            v-for="(item, index) in dataTree"
                            :key="index"
                            class="search-detail"
                            type="text"
                            @click="clickSearch(item)">
                            {{ item.name }}
                            <span :class="item.is_local ? 'local-color' : 'detail-color'">
                                {{ item.is_local ? '(本地)' : '(企微)' }}
                            </span>
                        </el-button>
                    </div>
                    <!-- <div v-if="dataTree.length == 0 && companySearch" class="no-data">
                      <div class="no-img">
                        <span class="no_data_text">暂无数据</span>
                      </div>
                    </div> -->
                </div>
                <div v-show="Opendepart !== 1">
                    <div>
                        已选择的部门：
                        <div v-for="(item, index) in dialogMember" :key="index" class="select-detail select-details">
                            <div>{{ item.name }}</div>
                            <el-icon v-show="item.name" style="font-size: 25px" @click="deldelectDeparts(item)">
                                <circle-close />
                            </el-icon>
                        </div>
                    </div>
                </div>
            </div>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="cancelDep">取消</el-button>
                    <el-button type="primary" @click="depConfirmed">确定</el-button>
                </span>
            </template>
        </el-dialog>
        <!--选择标签弹框-->
        <el-dialog v-model="isopenTag" custom-class="app_dialog" title="选择标签" width="60%">
            <div>
                选择分组：
                <el-select
                    v-model="tagPrams.group_id"
                    placeholder="请选择分组"
                    :popper-append-to-body="false"
                    @change="changeTag">
                    <el-option v-for="item in tagGroup" :key="item.id" :label="item.name" :value="item.id"></el-option>
                </el-select>
                <div>
                    <el-checkbox-group v-model="tagsGroupIds" class="selected-tags">
                        <el-checkbox
                            v-for="(item, index) in tagsGroup"
                            :key="index"
                            :label="item.id"
                            class="tag-detail"
                            :disabled="item.source_type == 2">
                            {{ item.name }}
                        </el-checkbox>
                    </el-checkbox-group>
                </div>
                <el-button type="primary" class="add-tag-list" @click="addNewTags">新建标签</el-button>
            </div>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="closeTag">取消</el-button>
                    <el-button type="primary" @click="tagConfirm">确定</el-button>
                </span>
            </template>
        </el-dialog>
        <!--新建标签弹框-->
        <el-dialog v-model="isaddTags" custom-class="app_dialog" title="新建标签" width="25%" append-to-body>
            <div>
                <span class="add-tags">*</span>选择分组：<el-select
                    v-model="tagPrams.group_id"
                    placeholder="请选择分组"
                    :popper-append-to-body="false"
                    @change="changeTag">
                    <el-option v-for="item in tagGroup" :key="item.id" :label="item.name" :value="item.id"></el-option>
                </el-select>
                <div class="select-tags">
                    <div class="tags-title">
                        <span>标签名称:</span>每个标签名称最多15个字。同时新建多个标签时，请用"空格"隔开
                    </div>
                    <el-input
                        v-model="tagPrams.name"
                        maxlength="15"
                        show-word-limit
                        placeholder="请输入标签（不得超过15个字符）"></el-input>
                </div>
            </div>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="isaddTags = false">取消</el-button>
                    <el-button type="primary" @click="addTags">确定</el-button>
                </span>
            </template>
        </el-dialog>
        <Dialog :app-dialog="appDialog">
            <div class="contents">
                <el-form label-position="right" label-width="100px">
                    <el-form-item label="企微同步方式" class="form-item" :model="supersync">
                        <el-radio v-model="supersync.sync_super" :label="1">保留两者</el-radio>
                        <el-radio v-model="supersync.sync_super" :label="2">替换</el-radio>
                    </el-form-item>
                    <el-form-item v-if="supersync.sync_super == 1">
                        <div>
                            <div class="tips common">
                                <span>
                                    选择保留两者，将把企业微信官方组织架构同步至本地，已经通过
                                    <el-tooltip class="box-item" effect="light" virtual-ref>
                                        <template #content>
                                            <img src="@/assets/applys.png" alt="" />
                                        </template>
                                        <span id="spanRef" ref="spanRef" class="blue">
                                            应用授权
                                            <img src="@/assets/tips.png" alt="" style="vertical-align: text-bottom" />
                                        </span>
                                    </el-tooltip>
                                    的员工可通过相同手机号合并成一个企微员工，同时保留本地原有组织架构和员工不变；未通过授权的员工将以新的企微员工身份同步至本地，直至授权以后再通过手机号来合并企微员工。
                                </span>
                            </div>
                        </div>
                    </el-form-item>
                    <el-form-item v-if="supersync.sync_super == 2">
                        <div class="tips common">
                            <span>
                                选择替换，替换原先的组织架构，将以企业微信组织架构为基准，同步到本系统。若本地员工与企微员工为相同手机号，则自动变更为企微员工，且所在部门以企业微信为准。
                                <span class="danger">若您需要部分本地成员，不成为企业成员，请慎用。</span>
                            </span>
                        </div>
                    </el-form-item>
                    <el-form-item>
                        <span class="warn common">同步后，在本系统里依然可以创建本地部门和员工</span>
                    </el-form-item>
                </el-form>
            </div>
        </Dialog>
    </div>
    <!-- 开启子账号弹窗 -->
    <el-dialog
        v-model="subAccountVisible"
        custom-class="app_dialog"
        width="520px"
        :title="employeedData.length !== 0 ? '开启子账号' : employeeData.length !== 0 ? '批量开启子账号' : ''"
        draggable
        :before-close="btnCancel">
        <div class="account_content">
            <img src="/static/appmarket/tips.png" style="width: 36px; height: 36px; margin-right: 32px" />
            <div style="line-height: 20px; height: 43px">
                <p>
                    当前剩余子账号数量为
                    <span style="color: #ff6b00">
                        {{
                            remainingAmount?.remaining_account_count > 0 ? remainingAmount.remaining_account_count : 0
                        }}。
                    </span>
                    企微助手数量：
                    <span style="color: #ff6b00">
                        {{
                            remainingAmount?.remaining_work_wx_count > 0 ? remainingAmount.remaining_work_wx_count : 0
                        }}。
                    </span>
                </p>
                <p v-if="employeeData.length == 1">{{ `您确定为${'员工' + employeeData}开启子账号吗?` }}</p>
                <p v-if="employeeData.length == 2">
                    {{ `您确定为${'员工' + employeeData[0] + ',' + '员工' + employeeData[1]}开启子账号吗?` }}
                </p>
                <p v-if="employeeData.length > 2">
                    {{ `您确定为${employeeData.slice(0, 2)}等${employeeData.length}个员工开启子账号吗?` }}
                </p>
                <p v-if="employeedData.length">{{ `您确定为${'员工' + employeedData}开启子账号吗?` }}</p>
            </div>
        </div>
        <el-form
            ref="ruleFormRef"
            :rules="rulesaccount"
            label-width="100px"
            :model="formAccount"
            style="margin-left: 58px">
            <el-form-item label="账号角色" prop="role_id">
                <el-select v-model="formAccount.role_id" placeholder="请选择角色" class="split">
                    <el-option v-for="item in roleType" :key="item.id" :label="item.name" :value="item.id"> </el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="初始密码" prop="password">
                <el-input v-model="formAccount.password" placeholder="请输入密码" class="split" />
            </el-form-item>
            <el-form-item label="启用企微助手" prop="enable_assistant_options">
                <el-checkbox v-model="formAccount.enable_assistant_options" />
            </el-form-item>
        </el-form>
        <template #footer>
            <el-button type="primary" @click="btnCancel">取消</el-button>
            <el-button type="primary" @click="onSubmit">确定开启</el-button>
        </template>
    </el-dialog>
    <!-- 开启子账号成功弹唱 -->
    <el-dialog
        v-model="successAccountVisible"
        custom-class="app_dialog"
        width="520px"
        title="开启子账号"
        draggable
        :before-close="btnCancelAccount">
        <div class="account_content">
            <img src="/static/appmarket/rectangle.png" style="width: 36px; height: 36px; margin-right: 32px" />
            <div style="line-height: 20px; height: 43px">
                <p v-if="employeedData.length">{{ `您已成功为${'员工' + employeedData}开启子账号！` }}</p>
                <p v-if="employeeData.length == 1">{{ `您已成功为员工${employeeData}开启子账号！` }}</p>
                <p v-if="employeeData.length == 2">
                    {{ `您已成功为${'员工' + employeeData[0] + ',' + '员工' + employeeData[1]}开启子账号！` }}
                </p>
                <p v-if="employeeData.length > 2">
                    {{ `您已成功为${employeeData.slice(0, 2)}等${employeeData.length}个员工开启子账号！` }}
                </p>
                <p>
                    当前剩余子账号数量为
                    <span style="color: #ff6b00">{{ remainingAmount?.remaining_account_count }}。</span>
                    当前剩余企微助手数量：
                    <span style="color: #ff6b00"> {{ remainingAmount?.remaining_work_wx_count }}。 </span>
                </p>
            </div>
        </div>
        <template #footer>
            <el-button type="primary" @click="onSuccessAccount">确定</el-button>
        </template>
    </el-dialog>
    <TableDialog ref="TableDialogRef" @refreshTable="reloadTable" />
    <!-- 部门人员弹框 -->
    <ZWDepart ref="DepartRef" :has_authorization="1" :is_authorization="1" @determine="determine" />

    <!-- 高级设置 -->
    <Dialog :app-dialog="appConfiguration">
        <configurationCom ref="configurationComRef"></configurationCom>
    </Dialog>
</template>

<script lang="tsx" setup>
import ZwSearchForm from '@/components/zw/search-form/SearchForm';
import ZwTable from '@/components/zw/table/Table';
import TableDialog from './components/TableDialog.vue';
import ZWDrawer from './components/ZWDrawer.vue';
import Dialog from '@/components/Dialog.vue';
import ZWDepart from '@/components/ZWDepart.vue';
import configurationCom from './components/configurationCom.vue';
import { ElMessageBox, ElMessage, ElLoading } from 'element-plus';
import {
    superAsync,
    fetchTreeList,
    searchTreeList,
    queryAsync,
    addTreeList,
    delTreeList,
    addUserList,
    userTagList,
    userTagsList,
    userTagsAdd,
    updateDepartment,
    workUserDetail,
    putUserList,
    roleList,
    accountCount,
    subAccount,
    workUserList
} from '@/api/employe/employeemanage/manage';
import { ref, reactive, nextTick, watch, computed, onUnmounted } from 'vue';
import type { ElTreeV2 } from 'element-plus';
import { ISearch } from './type/index';
import { getSetionId } from '@/utils/utils';
import { deepCopy } from '@/utils/helper';
import { debounce } from 'lodash';
import { putAdvanceSetting } from '@/api/employe/employeemanage/manage';

//变量
import { useStore } from '@/store';
const subAccountVisible = ref<boolean>(false);
const successAccountVisible = ref<boolean>(false);
const employeeData = reactive([]);
const employeedData = reactive([]);
const ruleFormRef = ref();
// const DepartRef = ref(null)
const DepartRef = ref<HTMLElement | null>(null);
const roleType = ref([]);
const remainingAmount = ref();
const spanRef = ref(null);
const configurationComRef = ref(null);
const store = useStore();
const showEdit = ref(false); //是否展示部门编辑
// const dialogVisible = ref(false) //是否弹出添加部门
const departVisible = ref(false); //是否弹出选择部门
const DrawerRef = ref(null);
const isopenTag = ref(false); //是否弹出选择标签
const isaddTags = ref(false); //是否弹出新建标签
const Opendepart = ref(1); //1打开添加部门2打开添加成员3上级部门修改
const isEdit = ref(1); //1新建部门2编辑部门3添加部门
const department_id = ref();
const uploadForm = ref();
const companyName = ref();
const tableref = ref(null);
const companySearch = ref();
const departName = ref();
const treeData = ref([]); //部门树
const searchTree = ref([]);
const dataTree = ref([]);
const selectDeparts = ref([]); //选择的部门列表
const tagGroup = ref([]); //标签组列表
const tagsGroup = ref([]); //标签列表
const leaderdept = ref([]);
const updated_at = ref();
const isSuper = ref(1);
const qwasync = ref(true);
const editCount = ref(false); //编辑和预览为true 创建为false
const isread = ref(false); //true为预览false为编辑和创建
let rowdata = reactive({}); //表格行数据
const is_sub_account = ref(false);
const jobid = ref(null);
const dialogMember = ref([]); //弹框选中的。
const selectMembers = ref([]); //选择的
const tableRef = ref<any>(null);
const tagsGroupIds = ref([]); // 标签弹框列表
const loadingSync = ref<boolean>(false);
const tagPrams = reactive({
    name: '',
    group_id: ''
});
const selectDepartmant = reactive({
    name: '',
    pid: '',
    is_local: '',
    id: '',
    is_wx_dept_child: false,
    order: ''
});
const formInline = reactive({
    is_follow_user: '',
    status: '',
    is_local: '',
    name: ''
});
const formData = reactive({
    name: '',
    gender: 1,
    mobile: '',
    departments: [],
    tags: [],
    leader_dept: [],
    sync_work_wx: 1,
    id: ''
});
const formAccount = reactive({
    role_id: '',
    password: 'zyd123456',
    enable_assistant_options: true
});
const toWechatList = [
    {
        value: '0',
        label: '直接同步'
    },
    {
        value: '1',
        label: '高级同步'
    }
];

const rules = reactive({
    name: [
        {
            required: true,
            message: '请输入成员姓名',
            trigger: 'blur'
        }
    ],
    mobile: [
        {
            required: true,
            message: '请输入手机号',
            trigger: 'blur'
        },
        { min: 11, max: 11, message: '请输入11位手机号码', trigger: 'blur' }
    ],
    departments: [
        {
            required: true,
            message: '请选择部门',
            trigger: 'change'
        }
    ]
});
const rulesaccount = reactive({
    role_id: [
        {
            required: true,
            message: '请选择角色',
            trigger: 'change'
        }
    ],
    password: [
        {
            required: true,
            message: '密码不能为空',
            trigger: 'blur'
        }
    ]
});
const pagination = ref({
    currentPage: 1,
    pageSize: 15,
    total: 0
});
const treeProps = {
    value: 'id',
    label: 'name',
    children: 'children'
};
const defaultProps = {
    children: 'children',
    label: 'name'
};
const getRowKey = (row: any) => {
    return row.id;
};
// 高级同步取消
const cancelHandel = () => {
    appDialog.visible = false;
};
// 高级同步确定
const submitHandel = async () => {
    appDialog.visible = false;
    asyn();
};
const asyn = () => {
    superAsync({ type: supersync.sync_super }).then((res: any) => {
        jobid.value = res.id;
        queryResult(res.id);
    });
};
let loading: any = '';
let time: any = '';
const queryResult = async (id: any) => {
    await queryAsync({ job_id: id }).then((res: any) => {
        loading = ElLoading.service({
            lock: true,
            text: '同步中....',
            background: 'rgba(0, 0, 0, 0.7)'
        });
        if (!res.status) {
            loading.close();
            clearInterval(time);
            time = '';
            if (res.job_msg) {
                ElMessage.error(res.job_msg);
            } else {
                ElMessage.error('同步失败');
            }
            return;
        }
        if (res.status > 1) {
            loading.close();
            clearInterval(time);
            time = '';
            getTreeList();
            ElMessage[res.status == 2 ? 'success' : 'error'](res.status == 2 ? '同步成功' : '同步失败');
        } else {
            if (!time) {
                time = setInterval(() => {
                    queryResult(jobid.value);
                }, 3000);
            }
        }
    });
};
const appDialog = reactive({
    visible: false,
    showFootcontent: true,
    footContent: '2089-0908',
    title: '高级同步',
    width: '480px',
    cancel: cancelHandel,
    submit: submitHandel,
    cancelText: '取消',
    submitText: '确定'
});
const tips = ref(
    '选择保留两者，将把企业微信官方组织架构同步至本地，相同手机号的员工合并成一个企微员工，同时保留本地原有组织架构和员工不变'
);
const supersync = reactive({ sync_super: 1 });
//方法
watch(
    supersync,
    (oldvalue, newvalue) => {
        if (newvalue.sync_super == 1) {
            tips.value =
                '选择保留两者，将把企业微信官方组织架构同步至本地，相同手机号的员工合并成一个企微员工，同时保留本地原有组织架构和员工不变';
        } else if (newvalue.sync_super == 3) {
            tips.value =
                '选择合并，执行双向合并，即系统将把企业微信官方组织架构同步到本地，相同手机号员工合并成一个企微员工，相同组织架构合并为一个部门。同时，将本地已有组织架构和员工同步到企业微信官方。';
        } else {
            tips.value =
                '选择替换，替换原先的组织架构，将以企业微信组织架构为基准，同步到本系统。若本地员工与企微员工为相同手机号，则自动变更为企微员工，且所在部门以企业微信为准。';
        }
    },
    {
        deep: true
    }
);
//添加成员
const addUser = () => {
    uploadForm.value.validate(async (valid: any) => {
        if (valid) {
            if (editCount.value) {
                const param = is_sub_account.value
                    ? { ...formData, enable_assistant: Number(qwasync.value) }
                    : { ...formData };
                putUserList(param).then((data: any) => {
                    DrawerRef.value.drawer = false;
                    ElMessage({
                        message: '编辑成功',
                        type: 'success'
                    });
                });
            } else {
                addUserList(formData).then((data: any) => {
                    DrawerRef.value.drawer = false;
                    ElMessage({
                        message: '新增成功',
                        type: 'success'
                    });
                });
            }
        } else {
            ElMessage.error('请输入必填项！');
        }
    });
};
const departmentNames = ref(['', '']);
//搜索部门
const searchName = () => {
    if (DepartmentType.value == 2) {
        departmentNames.value[0] = companySearch.value;
    } else {
        departmentNames.value[1] = companySearch.value;
    }

    const params = {
        keyword: departVisible.value ? companySearch.value : companyName.value
    };
    searchTreeList(params).then((data: any) => {
        if (departVisible.value) {
            dataTree.value = data.length > 0 ? data : [];
        } else {
            searchTree.value = data.length > 0 ? data : [];
        }
    });
};
//鼠标移入
// const mouseOver = (data: any) => {
//   data.showEdit = true
// }
// //鼠标移出
// const mouseLeave = (data: any) => {
//   data.showEdit = false
// }
//获取部门树
const treeRef = ref<InstanceType<typeof ElTreeV2>>();
const elTreeHeight = ref(400);
const handleComputedHeight = () => {
    const navDom = document.querySelector('.content-total .left-nav');
    const treeDom = document.querySelector('.ant-tree.el-tree');
    if (navDom && treeDom) {
        elTreeHeight.value = navDom.clientHeight - (treeDom.offsetTop - navDom.offsetTop);
    }
};
// 自定义搜索
const handleSearch = debounce(() => {
    treeRef.value!.filter(companyName.value);
}, 500);
const handleFilterMethod = (query: string, node: any) => {
    return node.name!.includes(query);
};
const getTreeList = () => {
    treeData.value = [];
    fetchTreeList().then((data: any) => {
        treeData.value.push(data as never);
        updated_at.value = data.updated_at;
        treeRef.value?.setData([data]);
        const defaultExpandedKeys = [];
        for (const iterator of [data]) {
            if (iterator.children) {
                defaultExpandedKeys.push(iterator.id);
            }
        }
        treeRef.value?.setExpandedKeys(defaultExpandedKeys);
        nextTick(handleComputedHeight);
    });
};
getTreeList();
const selectId = ref(0);
const defSelected = ref([]);
//选择部门节点-负责部门
const nodeClick = (data: any, node?: any, obj?: any) => {
    selectId.value = data.id;
    search({ department_id: data.id });
    if (!departVisible.value) {
        department_id.value = data.id;
    } else {
        if (Opendepart.value == 1) {
            selectDepartmant.name = data.name;
            selectDepartmant.pid = data.id;
            selectDepartmant.is_local = data.is_local;
            departVisible.value = false;
        } else if (Opendepart.value == 2) {
            if (dialogMember.value.length > 0) {
                dialogMember.value.forEach((item: any) => {
                    if (item.id == data.id) {
                        return;
                    }
                });
            } else {
                dialogMember.value.push(data as never);
            }
            if (dialogMember.value.indexOf(data as never) == -1) {
                changeRadio(isSuper.value);
            }
        } else {
            if (dialogMember.value.indexOf(data as never) == -1) return;
        }
    }
    if (node.level == 1) {
        node.expanded = true;
    }
};

const onNodeExpand = (data: any, node: any) => {
    const treeDom = document.querySelector('.el-vl__window');
};

// 取消部门
const cancelDep = () => {
    departVisible.value = false;
    dialogMember.value = [];
};
// 部门确认
const depConfirmed = () => {
    switch (DepartmentType.value) {
        case 2:
            selectDeparts.value = dialogMember.value;
            formData.departments = getSetionId('id', selectDeparts.value);
            uploadForm.value.clearValidate('departments');

            break;
        case 3:
            leaderdept.value = dialogMember.value;
            formData.leader_dept = getSetionId('id', dialogMember.value);
            uploadForm.value.clearValidate('departments');
            break;
    }
    departVisible.value = false;
};
//添加部门
// const addMember = () => {
//   if (!departName.value) {
//     ElMessage.error('请输入部门名！')
//     return
//   } else if (isEdit.value == 3 && !selectDepartmant.name) {
//     ElMessage.error('请选择部门！')
//     return
//   }
//   if (isEdit.value != 2) {
//     const params = {
//       name: departName.value,
//       pid: selectDepartmant.pid,
//       is_local: selectDepartmant.is_local
//     }
//     addTreeList(params).then((data: any) => {
//       dialogVisible.value = false
//       ElMessage({
//         message: '新增成功',
//         type: 'success'
//       })
//       getTreeList()
//     })
//   } else {
//     const params = {
//       name: departName.value,
//       pid: selectDepartmant.pid,
//       id: selectDepartmant.id,
//       order: selectDepartmant.order
//     }
//     updateDepartment(params).then((data: any) => {
//       dialogVisible.value = false
//       ElMessage({
//         message: '编辑成功',
//         type: 'success'
//       })
//       getTreeList()
//     })
//   }
// }
//删除所选部门节点
const deldelectDeparts = (val: any) => {
    dialogMember.value.forEach((item: any) => {
        if (item.name == val.name) {
            dialogMember.value.pop();
            formData.departments.pop();
        }
    });
};
const DepartmentType = ref(2);
//打开选择部门
const Opendeparts = (val: number) => {
    DepartmentType.value = val;
    Opendepart.value = val;
    switch (val) {
        case 2:
            companySearch.value = departmentNames.value[0];
            dialogMember.value = JSON.parse(JSON.stringify(selectDeparts.value));
            break;
        case 3:
            companySearch.value = departmentNames.value[1];
            dialogMember.value = JSON.parse(JSON.stringify(leaderdept.value));
            break;
    }
    departVisible.value = true;
    searchName();
};
const openTagDialog = (val?: any) => {
    isopenTag.value = true;
    tagsGroupIds.value = val || [];
};
// 关闭标签弹框
const closeTag = () => {
    isopenTag.value = false;
    tagsGroupIds.value = [];
};
// 打开标签弹框
const tagConfirm = () => {
    isopenTag.value = false;
    formData.tags = JSON.parse(JSON.stringify(tagsGroupIds.value));
};
//删除tag
const handleClose = (tag: any, type: number) => {
    if (type == 1) {
        formData.departments = formData.departments?.filter((item: any) => item != tag.id);
        selectDeparts.value = selectDeparts.value?.filter((item: any) => item.id != tag.id);
        leaderdept.value = leaderdept.value?.filter((item: any) => item.id != tag.id);
        formData.leader_dept = formData.leader_dept?.filter((item: any) => item.id != tag.id);
    } else {
        leaderdept.value = leaderdept.value?.filter((item: any) => item.id != tag.id);
        formData.leader_dept = formData.leader_dept?.filter((item: any) => item != tag.id);
    }
};
//获取标签组列表
const getTagList = () => {
    userTagList().then((data: any) => {
        tagGroup.value = data;
        tagPrams.group_id = data[0].id;
    });
};
getTagList();
//获取标签列表
const getTagsList = (val: string) => {
    const params = {
        group_id: val
    };
    userTagsList(params).then((data: any) => {
        tagsGroup.value = data;
    });
};
getTagsList('');
//切换标签组列表
const changeTag = (data: any) => {
    nextTick(() => {
        getTagsList(data);
    });
};
//新增标签
const addTags = () => {
    if (!tagPrams.group_id) {
        ElMessage.error('请选择分组！');
        return;
    } else if (!tagPrams.name) {
        ElMessage.error('请输入标签名！');
        return;
    }
    const arr = tagPrams.name.split(/\s+/);
    arr.forEach((item: any) => {
        const params = {
            name: item,
            group_id: tagPrams.group_id
        };
        userTagsAdd(params).then((data: any) => {
            isaddTags.value = false;
            ElMessage({
                message: '新增成功',
                type: 'success'
            });
            getTagsList(tagPrams.group_id);
        });
    });
};
//同步
const changeLoading = () => {
    // if (res == 0) {
    // 直接同步
    loadingSync.value = true;
    superAsync({ type: 1 })
        .then((res: any) => {
            jobid.value = res.id;
            queryResult(res.id);
            loadingSync.value = false;
        })
        .catch(() => {
            loadingSync.value = false;
        });
    // } else {
    //   // 高级同步
    //   supersync.sync_super = 1
    //   appDialog.footContent = updated_at.value
    //   appDialog.visible = true
    // }
};
//新建标签
const addNewTags = () => {
    isaddTags.value = true;
    tagPrams.name = '';
    tagPrams.group_id = tagGroup.value[0].id;
};
//多选
const changeRadio = (val: any) => {
    isSuper.value = val;
    if (val == 2 || DepartmentType.value == 2) {
        formData.leader_dept = JSON.parse(JSON.stringify(formData.departments));
        leaderdept.value = JSON.parse(JSON.stringify(selectDeparts.value));
    } else {
        formData.leader_dept = [];
        leaderdept.value = [];
    }
};
//编辑员工
const is_local = ref();
const handleEdit = (value: any) => {
    is_local.value = value.is_local;
    is_sub_account.value = value.is_sub_account;
    qwasync.value = value.is_sub_account ? Boolean(value.enable_assistant) : true;
    if (value.type == 2) {
        isread.value = true;
        DrawerRef.value.title = '员工信息';
        DrawerRef.value.isShow = false;
    } else {
        DrawerRef.value.isShow = true;
        isread.value = false;
        DrawerRef.value.title = '编辑成员';
    }
    delete value.type;
    rowdata = value;
    if (uploadForm.value) {
        uploadForm.value.resetFields();
    }
    selectDeparts.value = [];
    formData.departments = [];
    formData.tags = [];
    formData.leader_dept = [];
    DrawerRef.value.width = 600;
    DrawerRef.value.drawer = true;
    editCount.value = true;
    formData.name = value.name;
    formData.gender = value.gender;
    formData.mobile = value.mobile;
    formData.leader_dept = value.leader_dept;
    formData.sync_work_wx = value.is_wx_follow_user;
    formData.id = value.id;
    getWorkerDetail(value.id);
};
//获取员工详情
const getWorkerDetail = (value: any) => {
    const params = {
        id: value
    };
    workUserDetail(params).then((data: any) => {
        selectDeparts.value = data.departments;
        if (data.departments.length > 0) {
            data.departments.forEach((element: any) => {
                formData.departments.push(element.id as never);
            });
        }

        if (data.tags.length > 0) {
            data.tags.forEach((element: any) => {
                formData.tags.push(element.id as never);
            });
        }
        if (data.leader_departments.length > 0) {
            data.leader_departments.forEach((element: any) => {
                formData.leader_dept?.push(element.id as never);
            });
        }
    });
};

const cancelConfigurationHandel = () => {
    appConfiguration.visible = false;
};
const submitConfigurationHandel = async () => {
    const res = configurationComRef.value?.submitFormExpose();
    const params = {
        department_list: res.department_list.map((v: any) => v.id),
        is_enable: res.is_enable
    };
    const result = await putAdvanceSetting(params);
    if (result) ElMessage.success('配置成功');

    appConfiguration.visible = false;
};

const appConfiguration = reactive({
    visible: false,
    showFootcontent: true,
    footContent: '',
    title: '高级配置',
    width: '650px',
    cancel: cancelConfigurationHandel,
    submit: submitConfigurationHandel,
    cancelText: '取消',
    submitText: '确定'
});

// 高级配置
const handleConfiguration = () => {
    appConfiguration.visible = true;
};
// 添加子账号
const addSubAccount = () => {
    DepartRef.value.appDialog.title = '选择员工';
    DepartRef.value.departVisble = true;
    DepartRef.value.isMember = true; // 可以选择部门
    // DepartRef.value.selectedMember = creators.value
};
// 获取角色列表
const role_id = ref();
const getRoleList = async () => {
    const res = await roleList({});
    res.forEach(item => {
        if (item.name == '超级管理员') {
            res.splice(item, 1);
        }
    });
    roleType.value = res;
};
// 获取子账号剩余数量
const getAccountCount = async () => {
    const res = await accountCount({});
    remainingAmount.value = res;
};
// 账号开启
const staff_id = ref([]);
const determine = async (val: any) => {
    val.forEach(item => {
        employeeData.push(item.name);
        staff_id.value.push(item.id);
    });
    if (DepartRef.value.currentData.length !== 0) {
        getRoleList();
        subAccountVisible.value = true;
        // DepartRef.value.departVisble = false
    } else {
        ElMessage.error('请选择员工');
    }
    getAccountCount();
};
const addSubAccountd = (v: any) => {
    employeedData.push(v.name);
    staff_id.value.push(v.id);
    getRoleList();
    getAccountCount();
    subAccountVisible.value = true;
};
// 确认添加子账号
const onSubmit = () => {
    if (employeeData.length > remainingAmount.value.remaining_account_count) {
        ElMessage.error('所选员工数量大于当前剩余子账号数量');
        return;
    }
    if (formAccount.enable_assistant_options) {
        if (employeeData.length > remainingAmount.value.remaining_work_wx_count) {
            ElMessage.error('所选员工数量大于当前剩余企微助手数量');
        }
    }
    ruleFormRef.value.validate(async (valid, fileds) => {
        if (valid) {
            const params = {
                work_user_list: staff_id.value,
                role_id: formAccount.role_id,
                password: formAccount.password,
                enable_assistant_options: formAccount.enable_assistant_options ? 1 : 0
            };
            await subAccount(params);
            getAccountCount();
            subAccountVisible.value = false;
            successAccountVisible.value = true;
        }
    });
};
const btnCancelAccount = () => {
    successAccountVisible.value = false;
};
// 提示成功子账号确认
const onSuccessAccount = () => {
    successAccountVisible.value = false;
    DepartRef.value.departVisble = false;
    DepartRef.value.selectedMember = [];
    DepartRef.value.searchName = '';
    DepartRef.value.currentData.length = 0;
    btnCancel();
};
// 取消
const btnCancel = () => {
    ruleFormRef.value.resetFields();
    roleType.value = [];
    employeeData.splice(0, employeeData.length);
    employeedData.splice(0, employeedData.length);
    staff_id.value = [];
    subAccountVisible.value = false;
};
//添加成员
const addPerson = () => {
    if (uploadForm.value) {
        uploadForm.value.resetFields();
    }
    isread.value = false;
    is_local.value = 1;
    DrawerRef.value.drawer = true;
    DrawerRef.value.isShow = true;
    DrawerRef.value.width = 600;
    DrawerRef.value.title = '添加员工';
    editCount.value = false;
    formData.name = '';
    formData.gender = 1;
    formData.mobile = '';
    formData.departments = [];
    formData.tags = [];
    formData.leader_dept = [];
    formData.sync_work_wx = 1;
    formData.id = '';
    selectDeparts.value = [];
    leaderdept.value = [];
    isSuper.value = 1;
};
//点击选择后的部门节点
const clickSearch = (data: any) => {
    // if (!departVisible.value) {
    //   department_id.value = data.id
    // } else {
    //   selectDeparts.value.filter((it: any) => it.id == data.id)
    // }
    nodeClick(data);
};

const operate = async (data: any) => {
    try {
        if (data == 1) {
            await TableDialogRef.value.del(rowdata);
        } else if (data == 2) {
            await TableDialogRef.value.tipsubmit(rowdata);
        } else if (data == 3) {
            await handleEdit({ ...rowdata, type: 1 });
        } else {
            await addUser();
        }
    } finally {
        setTimeout(() => tableRef.value.reload(), 200);
    }
};

const defaultParams = {
    is_wx_follow_user: '',
    status: '',
    is_local: '',
    name: ''
};

const state = reactive({
    searchParams: deepCopy(defaultParams),
    searchHeight: '112px'
});
const searchOption = computed(() => {
    return [
        {
            label: '外部联系人权限',
            name: 'is_wx_follow_user',
            value: '',
            type: 'select',
            placeholder: '请输入外部联系人权限',
            fetchOptionApi: () => {
                return new Promise(resolve => {
                    setTimeout(() => {
                        resolve([
                            { id: '2', name: '是' },
                            { id: '1', name: '否' }
                        ]);
                    }, 300);
                });
            },
            formatOption: (v: any) => ({
                label: v.name,
                value: v.id
            })
        },
        {
            label: '成员姓名',
            name: 'name',
            value: '',
            type: 'input',
            placeholder: '输入成员姓名'
        },
        {
            label: '成员状态',
            name: 'status',
            value: '',
            type: 'select',
            placeholder: '请选择成员状态',
            fetchOptionApi: () => {
                return new Promise(resolve => {
                    setTimeout(() => {
                        resolve([
                            { id: '1', name: '已激活' },
                            { id: '2', name: '已禁用' },
                            { id: '4', name: '未激活' },
                            { id: '5', name: '退出企业' }
                        ]);
                    }, 300);
                });
            },
            formatOption: (v: any) => ({
                label: v.name,
                value: v.id
            })
        },
        {
            label: '成员类型',
            name: 'is_local',
            value: '',
            type: 'select',
            placeholder: '请选择成员类型',
            fetchOptionApi: () => {
                return new Promise(resolve => {
                    setTimeout(() => {
                        resolve([
                            { id: '0', name: '企微' },
                            { id: '1', name: '非企微' }
                        ]);
                    }, 300);
                });
            },
            formatOption: (v: any) => ({
                label: v.name,
                value: v.id
            })
        }
    ];
});
const search = (v: any) => {
    tableRef.value.getTable().clearSelection();
    state.searchParams = { ...deepCopy(defaultParams), ...v, department_id: selectId.value };
};
const reset = (v: any) => {
    tableRef.value.getTable().clearSelection();
    state.searchParams = { ...deepCopy(defaultParams), department_id: selectId.value };
};
/**
 * @description: 展开收起
 */
const expandHandle = (expand: boolean) => {
    state.searchHeight = expand ? '112px' : '64px';
};

// 刷新表格
const reloadTable = () => {
    tableRef.value.reload();
};
// 表格
const tableOption = [
    {
        prop: 'id',
        label: '客易达员工ID',
        width: 160,
        render({ row }) {
            return row.id || '--';
        }
    },
    {
        prop: 'name',
        label: '企业成员',
        minWidth: 280,
        render({ row, column, index }) {
            return (
                <div>
                    <el-avatar
                        shape="square"
                        size={50}
                        src={row.avatar || 'https://img-scrm-dev.keyid.cn/keyid-scrm-server/avatar/cust_default.png'}
                        class="avatar"
                    />
                    {row.mobile ? `${row.name}(${row.mobile})` : row.name}
                    {row.gender == 0 ? (
                        <img class="sex" src="/static/customer/sex_0.png" alt="" />
                    ) : row.gender == 1 ? (
                        <img class="sex" src="/static/customer/sex_1.png" alt="" />
                    ) : row.gender == 2 ? (
                        <img class="sex" src="/static/customer/sex_2.png" alt="" />
                    ) : (
                        <div></div>
                    )}
                </div>
            );
        }
    },
    {
        prop: 'departments',
        label: '所在部门',
        align: 'left',
        minWidth: 200,
        isTag: true
    },
    {
        prop: 'tags',
        label: '成员标签',
        width: 220,
        isTag: true
    },
    {
        prop: 'is_local',
        label: '成员类型',
        align: 'left',
        width: 120,
        render({ row, column, index }) {
            return row.is_local == 1 ? '非企微' : '企微';
        }
    },
    {
        prop: 'status',
        label: '成员状态',
        align: 'left',
        width: 120,
        render({ row, column, index }) {
            return (
                {
                    '1': '已激活',
                    '2': '已禁用',
                    '4': '未激活'
                }[row.status] || '退出企业'
            );
        }
    },
    {
        prop: 'enable_assistant',
        label: '客易达应用',
        width: 100,
        render({ row }) {
            return row.enable_assistant == '1' ? '已启用' : '未启用';
        }
    },
    {
        prop: 'is_sub_account',
        label: '子账号',
        width: 100,
        render({ row }) {
            return row.is_sub_account ? '已关联' : '未关联';
        }
    },
    {
        prop: 'operate',
        label: '操作',
        width: 290,
        fixed: 'right',
        isOperate: true,
        option: [
            { name: '编辑', authCode: 'EDIT_STA_STACNETER', click: (row: any) => handleEdit({ ...row, type: 1 }) },
            { name: '预览', authCode: 'PRE_STACNETER', click: (row: any) => handleEdit({ ...row, type: 2 }) },
            {
                type: 'dropdown',
                menu: [
                    {
                        name: '删除',
                        isRender: ({ row }) => row.is_local != 0,
                        authCode: 'DEL_STACNETER',
                        click: (row: any) => handleClickDel(row)
                    },
                    { name: '保护客户', authCode: 'PROTECT_CUST', click: (row: any) => handleTipSubmit(row) },
                    {
                        name: '开启子账号',
                        isRender: ({ row }) => row.is_sub_account == false,
                        authCode: 'PROTECT_CUST',
                        click: (row: any) => handleAddSubAccountd(row)
                    }
                ]
            }
        ]
    }
];

const TableDialogRef = ref();
const handleClickDel = (row: any) => {
    TableDialogRef.value.del(row);
};
const handleTipSubmit = (row: any) => {
    TableDialogRef.value.tipsubmit(row);
};
const handleAddSubAccountd = (row: any) => {
    addSubAccountd(row);
};

const fetchApi = () => {
    // 获取文件列表
    // return getFissionList
    return workUserList;
};
</script>

<style lang="scss" scoped>
@import './index';

:deep(.zw-tree-box) {
    .el-vl__wrapper {
        position: initial;
        overflow-x: scroll;

        .el-vl__window {
            width: 700px;
        }
    }
}
</style>
